<!--文件上传-->
<template>
  <div class="upload-file">
    <el-upload
      multiple
      action=""
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :http-request="handleUploadRequest"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
      ref="fileUpload"
      :disabled="disabled"
    >
      <!-- 上传按钮 -->
      <slot name="upload">
        <el-button type="primary" :disabled="disabled">选取文件</el-button>
      </slot>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileTypes">
        格式为 <b style="color: #f56c6c">{{ [...fileTypes].join("/") }}</b>
      </template>
      的文件
    </div>
    <!-- 文件列表 -->
    <transition-group
      v-if="listOfFiles"
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li :key="index" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <el-link href="" :underline="false" target="_blank" @click="attachmentDownload(file)">
          <span class="el-icon-document"> {{ getFileName(file.fileName) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action" v-if="!disabled">
          <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
        </div>
      </li>
    </transition-group>
    <!-- 进度条 -->
    <el-progress v-if="uploading" :percentage="percentage" />
    <!-- 视频播放   -->
    <videoPopup ref="videoPopupRef" :video-address="videoAddress" />
  </div>
</template>

<script setup>
import {last} from "lodash-es"
import { getToken } from "@/utils/auth";
import Conf from "@/utils/conf";
import { ElMessage, ElMessageBox } from "element-plus";
import { attachmentPreview, getAttachmentDetail } from "@/api/navigationLecture";
import videoPopup from "@/components/Dialog/videoPopup";
import { TEACHING_FILE_TYPE } from "@/utils/constConfig";
const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 999, // 默认设置最大为999 不做限制
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型
  fileTypes: {
    type: Set,
    default: new Set(TEACHING_FILE_TYPE),
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  // 文件上传禁用状态
  disabled: {
    type: Boolean,
    default: false,
  },
  // 上传文件列表
  fileList: {
    type: Array,
    default: [],
  },
  // 文件列表展示状态
  listOfFiles: {
    type: Boolean,
    default: true,
  },
  // 进度条
  uploading: {
    type: Boolean,
    default: false,
  },
  // 进度条对应的百分比
  percentage: {
    type: Number,
    default: 0,
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const baseUrl = Conf.VITE_APP_BASE_API;
const uploadFileUrl = ref(Conf.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const showTip = computed(() => props.isShowTip && props.fileSize);
const videoPopupRef = ref(); // 视频弹窗ref值
const videoAddress = ref(""); // 视频播放地址

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      const temp = { value: 1 };
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(",");
      // 然后将数组转为对象数组
      props.fileList = list.map((item) => {
        if (typeof item === "string") {
          item = { name: item, url: item };
        }
        item.uid = item.uid || new Date().getTime() + temp.value++;
        return item;
      });
    }
    // TODO 如果是自定义上传 不需要清空文件列表 注释掉  如果是上传文件服务器地址 则打开
    // else {
    //   props.fileList = [];
    //   return [];
    // }
  },
  { deep: true, immediate: true },
);

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  const fileName = file.name.split(".");
  const fileExt = last(fileName);
  // 判断文件类型 是否在允许范围内 后缀名转换为小写
  const isTypeOk = props.fileTypes.has(fileExt.toLowerCase());
  if (!isTypeOk) {
    proxy.$modal.msgError(`文件格式不正确, 请上传${[...props.fileTypes].join("/")}格式文件!`);
    return false; // 拦截上传
  }
  // 校检文件大小
  if (props.fileSize && file.size > props.fileSize * 1024 * 1024) {
    proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
    return false; // 拦截上传
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  number.value++;
  return true;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadRequest(fileList) {
  emit("handleUploadRequest", fileList);
}

/**
 * 附件下载
 */
const attachmentDownload = async (file) => {
  try {
    proxy.$modal.loading("请稍候...");
    if (props.fileTypes.has("mp4")) {
      const { data } = await getAttachmentDetail(file.id);
      videoAddress.value = data.videoPlayPath;
      proxy.$refs?.videoPopupRef.show(true);
      return;
    }
    const { data } = await attachmentPreview({ id: file.id });
    window.open(data, "_blank"); // 打开链接下载
  } catch (error) {
    //TODO 框架已经做统一处理。
  } finally {
    proxy.$modal.closeLoading();
  }
};

// 删除文件
async function handleDelete(index) {
  try {
    await ElMessageBox.confirm("确认删除当前文件?", "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    emit("handleDelete", index);
    return true; // 返回true 则继续删除
  } catch {
    return false; // 返回false 则阻止删除
  }
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    props.fileList = props.fileList.filter((f) => f.url !== undefined).concat(uploadList.value);
    uploadList.value = [];
    number.value = 0;
    emit("update:modelValue", listToString(props.fileList));
    proxy.$modal.closeLoading();
  }
}

// 获取文件名称
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator = ",") {
  const urls = list.map((item) => item.url).filter(Boolean);
  return urls.join(separator);
}

// 清空文件列表
const handelClear = () => {
  proxy.$refs.fileUpload?.clearFiles();
};

defineExpose({
  handelClear,
});
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
